package net.zjitc.controller;

import net.zjitc.pojo.Category;
import net.zjitc.service.CategoryService;
import net.zjitc.service.impl.CategoryServiceImpl;
import net.zjitc.utils.dispacher.URLMapping;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * Created by rj1502 on 2017/11/14.
 */
public class AdminCategory {
    CategoryService service = new CategoryServiceImpl();
    /*查询所有的一级分类*/
    @URLMapping(url = "/AdminCategoryFindAll")
    public String findAll(HttpServletRequest request, HttpServletResponse response){
        List<Category>   list = service.findAll();
        request.setAttribute("list",list);
        return "/admin/category/list.jsp";
    }

    /**
     * 添加页面
     */
    @URLMapping(url = "/AdminCategoryAddUI")
    public String addUI(HttpServletRequest request, HttpServletResponse response) {

        return "/admin/category/addUI.jsp";
    }
    /**添加一级分类*/
    @URLMapping(url = "/AdminCategoryAdd")
    public String add(HttpServletRequest request, HttpServletResponse response) {
        Category category = new Category();
        try {
            BeanUtils.populate(category,request.getParameterMap());
            int count = service.insert(category);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = request.getContextPath()+"/AdminCategoryFindAll";
        return "Redirect:"+url;
    }

    /**
     * 回显数据
     * @param request
     * @param response
     * @return
     */
    @URLMapping(url = "/AdminCategoryEditUI")
    public String editUI(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        Category category = service.findByCid(cid);
        request.setAttribute("category",category);
        return "/admin/category/editUI.jsp";
    }

    /**
     * 修改数据
     * @param request
     * @param response
     * @return
     */
    @URLMapping(url = "/AdminCategoryEdit")
    public String edit(HttpServletRequest request, HttpServletResponse response){
        Category category = new Category();
        try {
            BeanUtils.populate(category,request.getParameterMap());
            int count =service.update(category);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = request.getContextPath()+"/AdminCategoryFindAll";
        return "Redirect:"+url;
    }

    /**
     * 删除数据
     * @param request
     * @param response
     * @return
     */

    @URLMapping(url = "/AdminCategoryDelete")
    public String delete(HttpServletRequest request, HttpServletResponse response){
        String cid = request.getParameter("cid");
        int count = service.delete(cid);
        String url = request.getContextPath()+"/AdminCategoryFindAll";
        return "Redirect:"+url;
    }
}
